package su.levenetc.ohos.draggableview.utils;

import ohos.agp.components.Component;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by Eugene Levenetc.
 */
public class Utils {
    public static float dpToPx(float dp, Context context) {
        if (dp <= 0) return 0;
        return (int) (context.getResourceManager().getDeviceCapability().screenDensity / 160 * dp);
    }

    public static boolean isViewContains(Component view, int x, int y, boolean useLocOnScreen) {

        int viewX;
        int viewY;

        if (useLocOnScreen) {
            int[] loc = new int[2];
            loc = view.getLocationOnScreen();
            viewX = loc[0];
            viewY = loc[1];
        } else {
            viewX = (int) view.getContentPositionX();
            viewY = (int) view.getContentPositionY();
        }

        int viewWidth = view.getWidth();
        int viewHeight = view.getHeight();
        return !(x < viewX || x > viewX + viewWidth || y < viewY || y > viewY + viewHeight);
    }

    public static float getTouchX(TouchEvent touchEvent, Component component) {
        return getTouchX(touchEvent, component, 0);
    }

    public static float getTouchX(TouchEvent touchEvent, Component component, int index) {
        float touchX = 0;
        if (touchEvent.getPointerCount() > index) {
            int[] xy = component.getLocationOnScreen();
            if (xy != null && xy.length == 2) {
                touchX = touchEvent.getPointerScreenPosition(index).getX() - xy[0];
            } else {
                touchX = touchEvent.getPointerPosition(index).getX();
            }
        }
        return touchX;
    }

    public static float getTouchY(TouchEvent touchEvent, Component component) {
        return getTouchY(touchEvent, component, 0);
    }

    public static float getTouchY(TouchEvent touchEvent, Component component, int index) {
        float touchY = 0;
        if (touchEvent.getPointerCount() > index) {
            int[] xy = component.getLocationOnScreen();
            if (xy != null && xy.length == 2) {
                touchY = touchEvent.getPointerScreenPosition(index).getY() - xy[1];
            } else {
                touchY = touchEvent.getPointerPosition(index).getY();
            }
        }
        return touchY;
    }
}
